package server

import (
	"context"
	"strings"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
	"github.com/go-kratos/kratos/v2/transport"
	jwt2 "github.com/golang-jwt/jwt/v5"

	"gitee.com/architect-training/substitute-driver/customer-srv/internal/service"
)

func customerJWT(customerSrv *service.CustomerService) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req any) (any, error) {
			// 获取存储在 JWT 中的用户 ID
			claims, ok := jwt.FromContext(ctx)
			if !ok {
				// 没有获取到 claims
				return nil, errors.Unauthorized("UNAUTHORIZED", "claims not found")
			}
			// 使用断言
			claimMap := claims.(jwt2.MapClaims)
			log.Info(claimMap)
			id := claimMap["jti"]
			// 获取 id 对应的顾客的 token
			token, err := customerSrv.CustomerDao.GetToken(id.(string))
			if err != nil {
				return nil, errors.Unauthorized("UNAUTHORIZED", "customer token not found")
			}

			// 比对数据表 token 和请求的 token
			header, _ := transport.FromServerContext(ctx)
			auths := strings.SplitN(header.RequestHeader().Get("Authorization"), " ", 2)
			jwtToken := auths[1]
			if jwtToken != token {
				return nil, errors.Unauthorized("UNAUTHORIZED", "token is falsified")
			}

			// 下一个中间件处理
			return handler(ctx, req)
		}
	}
}
